package com.david.bluetooth.ble.musicctr

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.david.bluetooth.R
import com.david.bluetooth.ble.musicctr.BleServerMusicService.Companion.MUSIC_ACTION_SERVICE_BLE_ADVERTISING

//使用bleService的activity
class MusicServerActivity: AppCompatActivity() {

    lateinit var tipsView: TextView
    lateinit var connectView: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music_server)
        tipsView = findViewById(R.id.tips)
        connectView = findViewById(R.id.music_server_connect)

        findViewById<View>(R.id.music_server_start_advertising).setOnClickListener {
            var intent = Intent(this, BleServerMusicService::class.java)
            intent.putExtra(BleServerMusicService.MUSIC_ACTION_SERVICE_ACTION_KEY, MUSIC_ACTION_SERVICE_BLE_ADVERTISING)
            startForegroundService(intent)
        }

        BleServerMusicService.onActionResultListener = object: OnTipsChangeListener {
            override fun onConnectChange(connectStatus: Boolean) {
                Log.e("ble", "onConnectChange: $connectStatus")

                runOnUiThread {
                    connectView.text = if (connectStatus) "已连接" else "未连接"
                }
            }

            override fun onTipsChange(tips: String) {
                Log.e("ble", "onTipsChange: $tips")

                runOnUiThread {
                    tipsView.text = tips
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        BleServerMusicService.onActionResultListener = null
    }
}